package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.MyConsigneeAddress;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.DoubleButtonDialog;
import com.flycent.hqhs.ui.view.RefreshViewItemClickWrapper;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.ui.view.SimpleTitleBar;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 * 选择地址
 */
public class ChoiceAddressActivity extends BackableTitleBarActivity implements 
OnLoadDataActionListener,OnItemClickListener,OnItemLongClickListener{

	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private List<MyConsigneeAddress> mConsigneeAddresses;
	String orderProperty = "createDate";
	private int nowPage = 1;
	private MyChoiseAddressAdapter mAdapter;
	private DoubleButtonDialog mAddressDeleteDialog;
	private long mAddressId;
	private long uid;
	private Handler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_choice_address);
		getTitleBar().setTitle(getString(R.string.title_order_choise_address));
		FinalActivity.initInjectedView(this);

		mAddressId = getIntent().getLongExtra("AddressId",0);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.choise_address_list);
		mRefreshListView.setOnItemClickListener(new RefreshViewItemClickWrapper.OnItemClickListener(this));
		mRefreshListView.getRefreshableView().setOnItemLongClickListener(
				new RefreshViewItemClickWrapper.OnItemLongClickListener(this));

		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		mAdapter = new MyChoiseAddressAdapter(this,R.layout.item_choise_address);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();


	}

	@Override
	public void onRefresh(int page) {
		updateAddressList(1, true);

	}

	@Override
	public void onLoadMore(int page) {
		nowPage++;
		updateAddressList(nowPage, false);
	}


	public class MyChoiseAddressAdapter extends AbsViewHolderAdapter<MyConsigneeAddress>{

		public MyChoiseAddressAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, MyConsigneeAddress itemData) {

			LinearLayout mlay = getViewFromHolder(R.id.item_choise_adress_main_lin);
			TextView mName = getViewFromHolder(R.id.choise_address_name_text);
			TextView mTel = getViewFromHolder(R.id.choise_address_tel_text);
			TextView mAddrss = getViewFromHolder(R.id.choise_address_detail_text);
			ImageView mImg = getViewFromHolder(R.id.address_is_choice_img);

			if( itemData.getIsDefault()){
				mlay.setBackgroundResource(R.drawable.setting_main_loyout_is_default);
			}else {
				mlay.setBackgroundResource(R.drawable.setting_main_loyout_selector);
			}

			if( itemData.getId() == mAddressId){
				mImg.setVisibility(View.VISIBLE);
			}else {
				mImg.setVisibility(View.GONE);
			}

			mName.setText(itemData.getConsignee());
			mTel.setText(itemData.getPhone());
			mAddrss.setText(itemData.getAreaName()+itemData.getAddress());

		}

	}

	private void updateAddressList(final int pageNum,final boolean isRefresh){

		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(ChoiceAddressActivity.this);

					PageEntity<MyConsigneeAddress> entry = client.receiver(pageNum, 10, orderProperty, "desc");

					int totlePage = entry.getTotalPages();
					mConsigneeAddresses = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						return;
					}
				} catch (WebException e) {
					if (e.getStatusCode() == WebException.TYPE_SERVER_RETURN_NULL)
						mConsigneeAddresses = null;
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		mLoadMoreProxy.loadDataActionComplete(true);

	}

	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{
		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}

		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if(mActivity.get() != null ){

				switch (msg.what) {
				case 0:
					mAdapter.update(mConsigneeAddresses);
					break;
				case 1:
					mAdapter.append(mConsigneeAddresses);
					break;
				case 2:
					dismissLoadingDialog();
					onRefresh(1);
					break;

				default:
					break;
				}
			}

		}
	}



	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position,
			long id) {
		new AlertDialog.Builder(this).setSingleChoiceItems(
				new String[] { "修改", "删除" }, 0,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0) { //修改
							toNewAddressActivity(position);
						}else {
							ShowDeleteDialog(position);
						}
						dialog.dismiss();
					}

				}).setNegativeButton("取消", null).show();



		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		uid = mAdapter.getData().get(position).getId();

		Intent intent = new Intent();  
		intent.putExtra("mid", uid);
		setResult(100, intent);  
		finish();

	}

	private void ShowDeleteDialog(final int pos ) {

		dismissDeleteDialog();
		mAddressDeleteDialog = new DoubleButtonDialog(this);
		mAddressDeleteDialog.showDialog(getString(R.string.info_delet_this_search), new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showLoadingDialog("");

				new Thread(){
					public void run() {
						try {
							WebClient.getInstance(ChoiceAddressActivity.this).receiverDelete(mAdapter.getData().get(pos).getId()+"");
							mHandler.sendEmptyMessage(2);
						} catch (WebException e) {
							dismissLoadingDialog();
							e.printStackTrace();
						}
					};
				}.start();
			}
		});


	}


	private void dismissDeleteDialog() {
		if( mAddressDeleteDialog != null && mAddressDeleteDialog.isShowing() ) {
			mAddressDeleteDialog.dismiss();
		}
		mAddressDeleteDialog = null;

	}

	/**
	 * 修改地址
	 * @param pos
	 */
	private void toNewAddressActivity(int pos) {

		Intent intent = new Intent(ChoiceAddressActivity.this,NewAddressActivity.class);
		intent.putExtra("inputType", "modify");

		intent.putExtra("id", mAdapter.getData().get(pos).getId()+"");
		intent.putExtra("consignee", mAdapter.getData().get(pos).getConsignee());
		intent.putExtra("areaName", mAdapter.getData().get(pos).getAreaName());
		intent.putExtra("phone", mAdapter.getData().get(pos).getPhone());
		intent.putExtra("address", mAdapter.getData().get(pos).getAddress());
		intent.putExtra("marea", mAdapter.getData().get(pos).getArea().getId()+"");
		intent.putExtra("zipCode", mAdapter.getData().get(pos).getZipCode());
		intent.putExtra("isDefault", mAdapter.getData().get(pos).getIsDefault());

		startActivity(intent);

	}
	@Override
	protected void onResume() {
		super.onResume();
		onRefresh(1);
	}

	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);

		titleBar.setRightButtonText(R.string.title_address_manager_right);

		titleBar.setOnRightButtonClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(ChoiceAddressActivity.this,NewAddressActivity.class);
				intent.putExtra("from", "ChoiceAddressActivity");
				intent.putExtra("inputType", "add");
				startActivity(intent);
			}

		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}


}
